<template>
  <div class="create-role w100 h100">
    <div class="module-tree">
      <vue-scroll>
        <div class="common-title"><span></span>平台权限树</div>
        <el-tree class="_tree"
                 v-loading="loading"
                 show-checkbox
                 default-expand-all
                 highlight-current
                 node-key="id"
                 :default-checked-keys="platformDefaultChecked"
                 :expand-on-click-node="false"
                 ref="platformTree" :data="platformTree" :props="defaultProps" @check="checkChange">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span><i class="el-icon-tickets" v-if="data.type !== 2" style="margin-right: 5px"></i>{{ node.label }}</span>
          </span>
        </el-tree>
        <div class="common-title" style="margin-top: 20px"><span></span>APP权限树</div>
        <el-tree class="_tree"
                 v-loading="loading"
                 show-checkbox
                 default-expand-all
                 highlight-current
                 node-key="id"
                 :default-checked-keys="appDefaultChecked"
                 :expand-on-click-node="false"
                 ref="appTree" :data="appTree" :props="defaultProps" @check="checkChange">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span><i class="el-icon-tickets" v-if="data.type !== 2" style="margin-right: 5px"></i>{{ node.label }}</span>
          </span>
        </el-tree>
      </vue-scroll>
    </div>
    <div class="role-info">
      <vue-scroll>
        <div class="common-title"><span></span>基本信息</div>
        <div class="form-container">
          <el-form :model="roleForm" :rules="rules" ref="roleForm" label-width="100px" class="demo-form">
            <el-form-item label="角色权重" prop="sort">
              <el-input v-model.number="roleForm.sort" :disabled="$route.path.includes('edit')"></el-input>
            </el-form-item>
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="roleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="角色编码" prop="code">
              <el-input v-model="roleForm.code"></el-input>
            </el-form-item>
            <el-form-item label="角色类型" prop="type">
              <el-select v-model="roleForm.type" placeholder="请选择角色类型">
                <el-option :label="item.label" :value="item.value" v-for="(item, index) in ROLE_TYPE_ENUM" :key="index"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="角色描述" prop="remark">
              <el-input type="textarea" v-model="roleForm.remark"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="cancel" class="cancel-btn function-btn">取  消</el-button>
            <el-button type="primary" @click="sure('roleForm')" class="function-btn">确  定</el-button>
          </div>
        </div>
      </vue-scroll>
    </div>
  </div>
</template>

<script>
  import Config from '../../../../config'
  import { mapGetters, mapMutations } from 'vuex'
  export default {
    name: 'createRole',
    props: {
      form: {
        type: Object,
        default: function () {
          return {
            sort: 0,
            name: '',
            code: '',
            type: '',
            remark: ''
          }
        }
      },
      title: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        roleForm: JSON.parse(JSON.stringify(this.form)),
        rules: {
          sort: [
            { required: true, message: '请填写角色权重', trigger: 'blur' },
            {type: 'number', message: '角色权重必须为数字值', trigger: 'blur'}
          ],
          name: [
            { required: true, message: '请填写角色名称', trigger: 'blur' }
          ],
          code: [
            { required: true, message: '请填写角色编码', trigger: 'blur' }
          ],
          type: [
            { required: true, message: '请选择角色类型', trigger: 'change' }
          ],
          remark: [
            { required: true, message: '请填写角色描述', trigger: 'blur' }
          ]
        },
        platformTree: [], // 平台权限树
        platformDefaultChecked: [], // 平台默认选中
        appTree: [], // app权限树
        appDefaultChecked: [], // app默认选中
        loading: true,
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        ROLE_TYPE_ENUM: [
          {
            label: '管理员',
            value: 0
          },
          {
            label: '用户',
            value: 1
          }
        ]
      }
    },
    computed: {
      ...mapGetters('user', {
        role: 'getRole'
      })
    },
    mounted () {
      if (this.$route.path.includes('edit')) {
        this.getRole()
        this.getModuleByRoleId()
          .then(res => {
            this.getAllModule()
          })
        return
      }
      this.getAllModule()
    },
    methods: {
      ...mapMutations('user', [
        'setModule',
        'setButton'
      ]),
      /**
       * 根据id获取角色信息
       * */
      getRole () {
        const id = this.$route.params.id
        const url = `${Config.AUTH_URL}/role/getById`
        const param = {
          id
        }
        this.$http.get(url, param)
          .then(data => {
            this.roleForm = data
          })
      },
      /**
       * 获取所有的菜单
       * */
      getAllModule () {
        const url = `${Config.AUTH_URL}/menu/getAll`
        this.$http.get(url)
          .then(data => {
            this.appTree.splice(0)
            this.appTree = data.app
            this.platformTree.splice(0)
            this.platformTree = data.plate
            this.loading = false
          })
          .catch(e => {
            this.$message.warning('获取菜单数据失败')
            this.loading = false
          })
      },
      /**
       * 根据角色id获取菜单
       * */
      getModuleByRoleId () {
        return new Promise((resolve, reject) => {
          const url = `${Config.AUTH_URL}/getButtonByRoleIds`
          const param = {
            roles: this.$route.params.id
          }
          this.$http.get(url, param)
            .then(data => {
              console.log('data ', data)
              this.platformDefaultChecked.splice(0)
              this.platformDefaultChecked = this.preHandleAppChecked(data.plate)
              this.appDefaultChecked.splice(0)
              this.appDefaultChecked = this.preHandleAppChecked(data.app)
              resolve()
            })
            .catch(e => {
              reject(e)
            })
        })
      },
      /**
       * 预处理被选中的节点，筛选出只是子节点的id
       * */
      preHandleAppChecked (arr) {
        const ids = []
        arr.forEach(item => {
          if (item.children.length === 0) {
            ids.push(item.id)
          }
        })

        return ids
      },
      cancel () {
        this.$router.go(-1)
      },
      sure (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.save()
          } else {
            this.$message(
              {
                message: '格式不正确',
                type: 'warning'
              }
            )
            return false
          }
        })
      },
      /**
       * 保存数据
       * */
      save () {
        let url = ``
        if (this.$route.path.includes('create')) {
          url += `${Config.AUTH_URL}/role/insertRoleAndMenu`
        } else {
          url += `${Config.AUTH_URL}/role/insertRoleAndMenu`
        }
        const param = this.roleForm
        const app = this.getCheckedNodes('appTree') // app模块
        const platform = this.getCheckedNodes('platformTree') // 平台模块
        param.menuIds = [].concat(app.menuIds, platform.menuIds)
        param.menuButtonRList = [].concat(app.menuButtonRList, platform.menuButtonRList)
        this.$http.post(url, param)
          .then(data => {
            this.$message.success('保存成功')
            this.$router.go(-1)
            this.updateNowUserModule(param)
            this.updateNowUserButton(param)
          })
          .catch(e => {
            console.log(e)
            this.$message.success('保存失败')
          })
      },
      /**
       * 获取树所有选中的节点
       * @param {String} value 数据组件的ref值
       * */
      getCheckedNodes (value) {
        const MODULE_PARENT = 1 // 父模块
        const MODULE_CHILD = 0 // 字模块
        const BUTTON = 2 // 按钮
        const nodes = this.$refs[value].getCheckedNodes().concat(this.$refs[value].getHalfCheckedNodes())
        const menuIds = []
        const menuButtonRList = []
        if (nodes.length === 0) {
          return {menuIds, menuButtonRList}
        }
        console.log('nodes ', nodes)
        nodes.forEach(node => {
          if (node.type === BUTTON) {
            menuButtonRList.push({
              buttonId: node.id,
              menuId: node.menuId
            })
          } else {
            menuIds.push(node.id)
          }
        })
        return {menuIds, menuButtonRList}
      },
      /**
       * 更新当前用户模块树(如果更新的是当前登录用户的模块，需要立马更新)
       * */
      updateNowUserModule (param) {
        const id = this.role[0].id
        if (id !== param.id) {
          return
        }
        const url = `${Config.AUTH_URL}/auth/getMenuByUserId`
        this.$http.get(url)
          .then(data => {
            this.setModule(data)
            console.log(data)
          })
      },
      /**
       * 更新当前用户模块树(如果更新的是当前登录用户的模块，需要立马更新)
       * */
      updateNowUserButton (param) {
        const id = this.role[0].id
        if (id !== param.id) {
          return
        }
        const url = `${Config.AUTH_URL}/getButtonByRoles`
        this.$http.get(url)
          .then(data => {
            this.setButton(data)
            console.log(data)
          })
      },
      /**
       * 每次点击都会打印tree所有选中的节点
       * */
      checkChange (data, obj) {
        const arr = [].concat(obj.halfCheckedNodes, obj.checkedNodes)
        console.log(arr)
      }
    }
  }
</script>

<style lang="scss" scoped>
  .create-role {
    display: flex;
    align-items: stretch;
    justify-content: flex-start;
    .module-tree {
      width: 430px;
      margin-right: 20px;
      background-color: #fff;
      border: 1px solid #E4E4E4;
      box-sizing: border-box;
      padding: 30px 0 30px 30px;
      ._tree {
        margin: 20px 0 0 20px;
      }
    }
    .common-title {
      font-size: 16px;
      font-weight: bold;
      color: #444;
    }
    .role-info {
      flex: 1;
      background-color: #fff;
      border: 1px solid #E4E4E4;
      box-sizing: border-box;
      padding: 30px 0 30px 30px;
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      .form-container {
        position: absolute;
        top: 50%;
        transform: translate(-50%, -50%);
        left: 50%;
        .demo-form {
          width: 340px;
        }
        .dialog-footer {
          height: 28px;
          text-align: center;
          margin-top: 30px;
          .el-button {
            padding: 7px 27px;
          }
        }
      }
    }
  }
</style>
